import { defineStore } from 'pinia'
import { getInfo, reqLogin, reqRegister, adminLogin } from '@/api/goods/index'
import { constantRoute, asyncRoute } from '@/router/route'
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'

// 递归添加嵌套路由
function addNestedRoutes(parentName: string, routes) {
  routes.forEach((route) => {
    if (!router.hasRoute(route.name)) {
      // 添加当前路由
      router.addRoute(parentName, {
        path: route.path,
        name: route.name,
        component: route.component,
        meta: route.meta,
      })

      // 递归处理子路由
      if (route.children?.length) {
        addNestedRoutes(route.name, route.children)
      }
    }
  })
}
export type UserRole = 'customer' | 'borrower' | 'brand' | 'admin'
const useUserStore = defineStore('User', {
  state: () => ({
    token: '',
    userName: '',
    role: 'customer',
    wallet: 0,
    avatar: '',
    status: '',
    signature: '',
    menuRoutes: constantRoute,
    showLoginDialog: false,
  }),
  getters: { isAuthenticated: (state) => !!state.token },
  actions: {
    async userLogin(name: string, password: string, selectRole: string) {
      if (selectRole === 'admin') {
        const result: any = await adminLogin(name, password)
        if (result.code === 0) {
          this.token = result.data
          this.role = selectRole

          // 深度克隆路由配置
          const filteredRoutes = this.filterAsyncRoute(cloneDeep(asyncRoute))

          // 动态添加路由
          this.addDynamicRoutes(filteredRoutes)

          // 更新菜单
          this.menuRoutes = [...constantRoute, ...filteredRoutes]
          this.hideLoginModal()
        }
      } else {
        const result: any = await reqLogin(name, password, selectRole)
        if (result.code === 0) {
          this.token = result.data
          this.role = selectRole

          // 深度克隆路由配置
          const filteredRoutes = this.filterAsyncRoute(cloneDeep(asyncRoute))

          // 动态添加路由
          this.addDynamicRoutes(filteredRoutes)

          // 更新菜单
          this.menuRoutes = [...constantRoute, ...filteredRoutes]
          this.hideLoginModal()
        } else {
          // 如果 result.code 不是 0，抛出错误
          throw new Error(result.message || '登录失败，用户名或密码错误');
        }
      }
    },
    async userRegister(
      userName: string,
      defaultName: string,
      userPassword: string,
      selectRole: string,
    ) {
      const result = await reqRegister(userName, defaultName, userPassword, selectRole)
      if (result.code == 0) {
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async userInfo() {
      const result = await getInfo()
      if (result.code === 0) {
        this.userName = result.data.username
        this.wallet = result.data.wallet
        this.status = result.data.status
        this.avatar = result.data.picture
        this.signature = result.data.personalInfo
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async userLogout() {
      this.token = ''
      this.userName = ''
      this.role = 'customer'
      this.wallet = 0
      this.avatar = ''
      this.status = ''
      this.signature = ''
    },

    // 增强路由过滤方法
    filterAsyncRoute(routes) {
      return routes.filter((route) => {
        // 验证角色权限
        const hasPermission =
          !route.meta.roles || (this.role && route.meta.roles.includes(this.role))

        if (hasPermission) {
          // 递归过滤子路由
          if (route.children) {
            route.children = this.filterAsyncRoute(route.children)
          }
          return true
        }
        return false
      })
    },

    // 安全添加路由
    addDynamicRoutes(routes) {
      routes.forEach((route) => {
        const parentName = route.meta.parentName || 'layout'

        if (!router.hasRoute(parentName)) {
          console.error(`父路由 ${parentName} 未注册`)
          return
        }

        // 添加路由及其嵌套路由
        addNestedRoutes(parentName, [route])
      })
    },
    showLoginModal() {
      this.showLoginDialog = true
    },
    hideLoginModal() {
      this.showLoginDialog = false
    },
  },
})
export default useUserStore
